require("ggplot2")
require("grid")
require("SDMTools")
library(extrafont)
create.demo.graph <- function(data, vars, vars.labels, comparisons, comparisons.labels, colors, weight.comparison) {
  #Specify data, variables to compare within (e.g., age, gender), string labels for the variables
  #what you are comparing across (e.g., phone vs. online), string labels for those comparisons
  #colors for the comparisons
  #a vector specifying whether a weighted mean should be used (0=no, 1=yes)
  comparisons <- rev(comparisons) #Need to reverse the order since graph is built from bottom up
  comparisons.labels <- rev(comparisons.labels) #Need to reverse the order since graph is built from bottom up
  colors <- rev(colors) #Need to reverse the order since graph is built from bottom up
  weight.comparison <- rev(weight.comparison) #Need to reverse order to match the other comparison
  #Build a dataframe for calculating mean and SEM of each variable across each comparison
  df <- matrix(NA, nrow=length(vars)*length(comparisons), ncol=10)
  df[,1] <- rep(vars, each = length(comparisons))
  df[,2] <- rep(vars.labels, each = length(comparisons))
  df[,3] <- rep(comparisons, times = length(vars))
  df[,4] <- rep(comparisons.labels, times = length(vars))
  df[,10] <- rep(colors, times = length(vars))
  df[,9] <- rep(weight.comparison, times = length(vars))
  for (i in 1:nrow(df)) {
  tryCatch({
  #Calculate the means
  #Hard code for starting universe
  if (df[i,3] == "all") df[i,5] <- mean(data[,df[i,1]])
  #Unweighted Mean
  if (is.na(df[i,9])) df[i,5] <- mean(data[which(!is.na(data[,df[i,3]])),df[i,1]], na.rm = TRUE)
  #Weighted Mean
  if (!is.na(df[i,9])) df[i,5] <- wt.mean(data[which(!is.na(data[,df[i,3]])),df[i,1]],
                                       data[,df[i,9]][which(!is.na(data[,df[i,3]]))])
  }, error=function(e){})
  }
  
  for (i in 1:nrow(df)) {
  tryCatch({
    #Calculate the SEM
    #Hard code for starting universe
    if (df[i,3] == "all") df[i,6] <- sd(data[,df[i,1]])/sqrt(length(data[,df[i,1]]))
    #Unweighted SEM
    if (is.na(df[i,9])) df[i,6] <- sd(data[which(!is.na(data[,df[i,3]])),
                                         df[i,1]], na.rm = TRUE)/sqrt(length(data[which(!is.na(data[,df[i,3]])),
                                                                    df[i,1]])) 
    #Weighted SEM
    if (!is.na(df[i,9])) df[i,6] <- wt.sd(data[which(!is.na(data[,df[i,3]])),
                                            df[i,1]],
                                       data[,df[i,9]][which(!is.na(data[,df[i,3]]))])/sqrt(length(data[which(!is.na(data[,df[i,3]])),
                                                                                                            df[i,1]]))
  }, error=function(e){})
  }
  df[,7] <- as.numeric(df[,5]) - as.numeric(df[,6])
  df[,8] <- as.numeric(df[,5]) + as.numeric(df[,6])
  df <- as.data.frame(df)
  df <- rename(df, c("V1" = "vars", "V2" = "vars.labels", "V3" = "comparisons", "V4" = "comparisons.labels", 
                                       "V5" = "mean", "V6" = "sem", "V7" = "lower", "V8" = "upper", "V9" = "weight",
                                       "V10" = "comparisons.color"))
  factor.list <- c("mean", "sem", "lower", "upper")
  for (i in factor.list) {
  df[,i] <- as.numeric(levels(df[,i])[df[,i]])
  }
  levels.list <- c("vars", "vars.labels", "comparisons", "comparisons.labels")
  for (i in levels.list) {
  df[,i] <- factor(df[,i], levels = get(i))
  }
  df$comparisons.color <- as.character(df$comparisons.color)
  
  # dot plot
  p <- ggplot(df, aes(x = mean, xmin = lower, xmax = upper, y = comparisons.labels, colour = comparisons)) +
    geom_point(size = .5) +
    scale_colour_manual(values = df$comparisons.color) +
    geom_errorbarh(aes(height = .5)) +
    facet_wrap(~ vars.labels, ncol = 5) +
    scale_x_continuous(limits = c(0,1), breaks = seq(0, 1, .25), 
                       labels = c(0, "", .5, "", 1)) + 
    labs(x = "Proportion of Characteristic", y = NULL) + 
    theme_bw() +
    theme(panel.grid.major.y = element_line(colour = "grey60"), 
          panel.grid.major.x = element_blank(),
          panel.grid.minor = element_blank(),
          panel.margin = unit(0, "lines"),
          strip.background = element_rect(fill = "grey80"),
          axis.ticks.y = element_blank(), 
          axis.text.y = element_text(color=colors),
          legend.position="none",
          text = element_text(family = 'Verdana')) +
    geom_vline(xintercept = 0)
    return(p)
}